﻿/*
题目: 二叉树的锯齿形层序遍历

给你二叉树的根节点 root ，返回其节点值的 锯齿形层序遍历 。（即先从左往右，再从右往左进行下一层遍历，以此类推，层与层之间交替进行）。

https://leetcode.cn/problems/binary-tree-zigzag-level-order-traversal/description/
*/

#include <iostream>
#include <random>
#include <string>
#include <vector>
#include <list>
#include "TreeNode.hpp"
#include "ListNode.hpp"
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
#include <functional>

using namespace std;

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        if (root == nullptr)    return {};

        vector<vector<int>> res;
        bool left2right = true;

        queue<TreeNode*> q;
        q.push(root);

        while (!q.empty()) {
            int size = q.size();
            int i = 0;
            vector<int> tmp(size);          // 每一层的大小都是固定的
            while (i++ < size) {
                TreeNode* nd = q.front();
                q.pop();

                tmp[left2right ? i - 1 : size - i] = nd->val;
                if (nd->left)   q.push(nd->left);
                if (nd->right)  q.push(nd->right);
            }
            left2right = !left2right;
            res.emplace_back(std::move(tmp));
        }

        return res;
    }
};
